package de.swta.freezay.admin.itemPackage;

import de.swta.freezay.admin.item.ItemView;
import de.swta.freezay.database.JPAController;
import de.swta.freezay.database.dbEntities.Item;
import de.swta.freezay.database.dbEntities.ItemPackage;
import de.swta.freezay.database.dbEntities.Package;
import de.swta.freezay.database.wicketAdapter.ItemDataProvider;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.NumberFormatter;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.DefaultDataTable;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

/**
 *
 * @author Jan
 */
public abstract class AddItemsToPackagePanel extends Panel {

    /** Formatter for numbers. */
    private static final NumberFormatter NUMBER_FORMATTER =
            new NumberFormatter(new DecimalFormat("####.##"));
    /** Webcontainer for the item list. */
    final WebMarkupContainer theContainer = new WebMarkupContainer("theContainer");
    /** Package content wich is edited. */
    private HashMap<Integer, Boolean> packageContent;
    /** Package to edit. */
    private Package p;
    /** EditMode is true if an package is edited, otherwise false. */
    private boolean editMode = false;

    /**
     * Creates a new instance of AddItemsToPackagePanel.
     *
     * @param id Id of the panel.
     * @param p Package to edit.
     * @param editMode true if an package is edited, otherwise false.
     */
    public AddItemsToPackagePanel(String id, Package p, boolean editMode) {
        super(id);

        this.editMode = editMode;
        this.p = p;
        init();
    }

    /**
     * Intializes all the components of the panel.
     */
    private void init() {

        this.packageContent = new HashMap<Integer, Boolean>();

        /** all columns of the dataTable. */
        ArrayList<IColumn> columns = new ArrayList<IColumn>();

        /* CheckBox if the item is in the package. */
        columns.add(new AbstractColumn(new Model("Enthalten")) {

            public void populateItem(org.apache.wicket.markup.repeater.Item cellItem, String componentId, IModel model) {
                final Item i = (Item) model.getObject();
                /* Panel which indicates a acheckbox. */
                cellItem.add(new PackageItemCheckBoxPanel(componentId, p.getId(),
                                i.getId(), AddItemsToPackagePanel.this.editMode) {

                    @Override
                    public void checkBoxValueChanged(AjaxRequestTarget target, Boolean value) {
                        AddItemsToPackagePanel.this.valueChanged(i.getId(), value);
                    }
                });
            }
        });

        columns.add(new PropertyColumn(new Model("Name"), "name"));
        columns.add(new PropertyColumn(new Model("Kategorie"), "category.name"));
        columns.add(new AbstractColumn(new Model("Menge")) {

            public void populateItem(org.apache.wicket.markup.repeater.Item cellItem, String componentId, IModel model) {
                Item i = (Item) model.getObject();
                try {
                    cellItem.add(new Label(componentId, "" + NUMBER_FORMATTER.valueToString(i.getAmount())));
                } catch (ParseException ex) {
                    Logger.getLogger(ItemView.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        columns.add(new PropertyColumn(new Model("Einheit"), "unit.name"));
        columns.add(new AbstractColumn(new Model("Preis")) {

            public void populateItem(org.apache.wicket.markup.repeater.Item cellItem, String componentId, IModel model) {

                Item i = (Item) model.getObject();
                try {
                    cellItem.add(new Label(componentId, "" + NUMBER_FORMATTER.valueToString(i.getPrice()) + " €"));
                } catch (ParseException ex) {
                    Logger.getLogger(AddItemsToPackagePanel.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

        columns.add(new AbstractColumn(new Model("Anzahl\n (verfügbar)")) {

            public void populateItem(org.apache.wicket.markup.repeater.Item cellItem, String componentId, IModel model) {
                Item i = (Item) model.getObject();

                cellItem.add(new Label(componentId, "" + i.getRemainingCount()));
            }
        });

        /* table for all items in the package. */
        ItemDataProvider provider = new ItemDataProvider();
        provider.setSort("category.name", true);
        final DefaultDataTable itemTable =
                new DefaultDataTable("itemTable", columns, provider,
                JPAController.ItemJpaController.getItemCount());

        theContainer.add(itemTable);
        theContainer.setOutputMarkupId(true);
        add(theContainer);

        /* Confirm link to save the package content (items). */
        add(new AjaxLink("confirm1") {

            @Override
            public void onClick(AjaxRequestTarget target) {
                onConfirm(target);
            }
        });
        /* Confirm link to save the package content (items). */
        add(new AjaxLink("confirm2") {

            @Override
            public void onClick(AjaxRequestTarget target) {
                onConfirm(target);
            }
        });

    }

    /**
     * Saves the content for a package.
     */
    public void savePackageContent() {
        Iterator<Integer> keyIt = this.packageContent.keySet().iterator();

        Integer actItemKey;

        while(keyIt.hasNext()) {
            actItemKey = keyIt.next();

            if (this.packageContent.get(actItemKey).booleanValue()) {
                /* item is selected */
                if (!p.containsItem(actItemKey)) {
                    /* item is new for package - add it when it is available. */
                    if (JPAController.ItemJpaController.findItem(actItemKey).getRemainingCount() >= p.getCount()) {
                        List<ItemPackage> packages = p.getItemPackageCollection();
                        packages.add(new ItemPackage(p.getId(), actItemKey, 1));
                    }
                }  /* other case - nothing. item was allready in. */
            } else {
                /* item has to removed - item vount is set to zero. */
                List<ItemPackage> packages = p.getItemPackageCollection();
                packages.get(packages.indexOf(new ItemPackage(p.getId(),
                                        actItemKey))).setItemCount(0);
                p.setItemPackageCollection(packages);
            }
        }
    }

    /**
     * Handles an action, when a value in a checkBox changed.
     *
     * @param itemId Id of an item.
     * @param value Boolean value of the checkBox.
     */
    private void valueChanged(Integer itemId, Boolean value) {
        this.packageContent.put(itemId, value);
    }

    /**
     * Handles the actions after the confirm button was clicked.
     * 
     * @param target AjaxRequestTarget.
     */
    public abstract void onConfirm(AjaxRequestTarget target);
}
